package mk.company.fin.model;

import java.util.List;

import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
//import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import javax.persistence.Transient;
import javax.persistence.UniqueConstraint;

import mk.company.fin.FinConstants;

import org.apache.commons.lang.StringUtils;
import org.hibernate.annotations.Index;

@Entity
@Table(name = FinConstants.Tables.KONTO_GROUP, 
		uniqueConstraints = {@UniqueConstraint(columnNames = {"value", "id_konto_class"})})
public class KontoGroup extends Model {

	private static final long serialVersionUID = -2911881094017253391L;

	// persistence
	private Long id;
	private String value;
	private String description;
	private KontoClass kontoClass;
	private List<KontoSynthetic> kontoSynthetics;
	
	// dynamic
	private String group;
	
	
	@Id
	@Column(name = "id_konto_group")
	@GeneratedValue//(strategy = GenerationType.SEQUENCE)
	public Long getId() {
		return id;
	}
	
	public void setId(Long id) {
		this.id = id;
	}

	@Column(nullable = false, length = 1)
	@Index(name = FinConstants.Tables.KONTO_GROUP + "_search")
	public String getValue() {
		return value;
	}

	public void setValue(String value) {
		if (StringUtils.isNotEmpty(value) && value.length() == 1) {
			this.value = value;
		}
	}

	@Column
	public String getDescription() {
		return description;
	}

	public void setDescription(String description) {
		this.description = description;
	}

	@ManyToOne(cascade = CascadeType.ALL, fetch = FetchType.EAGER)
	@JoinColumn(name = "id_konto_class", nullable = false)
	@Index(name = FinConstants.Tables.KONTO_GROUP + "_search")
	public KontoClass getKontoClass() {
		return kontoClass;
	}

	public void setKontoClass(KontoClass kontoClass) {
		this.kontoClass = kontoClass;
	}

	@OneToMany(mappedBy = "kontoGroup", orphanRemoval = true, fetch = FetchType.LAZY)
	public List<KontoSynthetic> getKontoSynthetics() {
		return kontoSynthetics;
	}

	public void setKontoSynthetics(List<KontoSynthetic> kontoSynthetics) {
		this.kontoSynthetics = kontoSynthetics;
	}
	
	
	/**
	 * @return the Class + Group of the Konto
	 */
	@Transient
	public String getGroup() {
		if (group == null) {
			KontoClass kontoClass = getKontoClass();
			if (kontoClass != null) {
				group = kontoClass.getValue() + getValue();
			} else {
				group = "?" + getValue();
			}
		}
		return group;
	}
	
	@Deprecated
	public void setGroup(String group) {
		throw new UnsupportedOperationException("The field group is dynamic!");
	}
	
	@Override
	public String toString() {
		return getGroup();
	}
}
